--
-- Author: shunguo.chen
-- Date: 2016-06-21 15:03:21
--
-- IMVoiceRender

local ClassRef = app.mvc.createRenderClass(...)

-- ClassRef._rcdNode = nil
-- ClassRef._rcdCancelNode = nil

function ClassRef.create(node, data)
	local sprite = ClassRef.extend(node)
	sprite:init(data)
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	local function onTouchEvent(sender, eventType)
		if eventType == ccui.TouchEventType.began then
			executeFunc(self._onTouchEvent, true)
			EM:notify("onRecordPhaseChange", Enums.IMRecordPhase.Start, self._data, self._onRecordEnd)
		elseif eventType == ccui.TouchEventType.moved then
			if self:isInRect(self:getTouchMovePosition()) then
	        	EM:notify("onRecordPhaseChange", Enums.IMRecordPhase.Record) 
	        else
				EM:notify("onRecordPhaseChange", Enums.IMRecordPhase.Cancel)
	        end
		elseif eventType == ccui.TouchEventType.canceled or eventType == ccui.TouchEventType.ended then
			EM:notify("onRecordPhaseChange", Enums.IMRecordPhase.End)
			self:setTouchEnabled(false)
			self:performWithDelay(function()
					self:setTouchEnabled(true)
				end, 0.5)

			executeFunc(self._onTouchEvent, false)
		end
	end
	self:addTouchEventListener(onTouchEvent)
end

-- 是否扩大rect范围
function ClassRef:setExtendRect(b)
	self._extendRect = b
end

function ClassRef:isInRect(pos)
	local rect = self._rect
	if not self._rect then
		rect = self:getBoundingBox()
		local worldPos = self:convertToWorldSpace(cc.p(0,0))
		if self._extendRect then
			rect.x = worldPos.x - 50
			rect.y = worldPos.y - 50
			rect.width = rect.width + 100
			rect.height = rect.height + 100
		else
			rect.x = worldPos.x
			rect.y = worldPos.y
		end

		self._rect = rect
	end

	return cc.rectContainsPoint(rect, pos)
end

function ClassRef:onRecordEnd(cb)
	self._onRecordEnd = cb
end

function ClassRef:onTouchEvent(cb)
	self._onTouchEvent = cb
end

return ClassRef